package com.kefu.chat.service;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Maps;
import com.kefu.chat.model.ChatAdmin;
import com.kefu.chat.model.ChatUser;
import com.kefu.chat.vo.ChatVideosInsertVo;
import com.kefu.chat.vo.ChatVideosSearchVo;
import com.kefu.common.context.KefuContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.chat.mapper.ChatVideosMapper;
import com.kefu.chat.model.ChatVideos;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.time.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author hxh
 * @date 2022/10/26
 */
@Service
public class ChatVideosService extends AbstractKefuService<ChatVideos> {
    @Autowired
    protected ChatVideosMapper chatVideosMapper;

    @Autowired
    private ChatCacheService chatCacheService;



    public String save(ChatVideosInsertVo chatVideosInsertVo){
        ChatVideos videos = chatVideosInsertVo.convert();
        ChatUser user = chatCacheService.getUser(chatVideosInsertVo.getUserId());
        if (user!=null){
            videos.setUserId(user.getUserId());
            videos.setUserName(user.getUserName());
        }
        ChatAdmin admin = chatCacheService.getAdmin(chatVideosInsertVo.getAgentId());
        if (admin!=null){
            videos.setAgentId(admin.getAdminId());
            videos.setAgentName(admin.getAdminName());
        }
        if (chatVideosInsertVo.getConversationId()!=null){
            videos.setConversationId(chatVideosInsertVo.getConversationId());
        }
        //设置接通时间
        videos.setThroughTime(chatVideosInsertVo.getThroughTime());
        //设置挂断时间
        videos.setTangTime(chatVideosInsertVo.getTangTime());
        //设置通话时间
        videos.setVideoTime(chatVideosInsertVo.getVideoTime());
        //设置通话流量
        if (chatVideosInsertVo.getVideoTime()!=null) {
            Double flow=200*chatVideosInsertVo.getVideoTime()/1024;
            //保留两位小数
            BigDecimal flowProcess = new BigDecimal(flow);
            double flowFinal = flowProcess.setScale(2, RoundingMode.HALF_UP).doubleValue();
            videos.setFlow(flowFinal);
        }
        if (videos.getConversationId()!=null&&!videos.getConversationId().equals("")){
            updateById(videos);
            return videos.getConversationId();
        }

        chatVideosMapper.insert(videos);
        String conversationId = videos.getConversationId();
        return conversationId;

    }

    public List<ChatVideos> videoStatistics(ChatVideosSearchVo vo) {
        
        Map<String,Object> param=Maps.newHashMap();
        param.put("tenantId", KefuContext.getKefuContext().getTenantId());
        if (vo.getStatisticsDateStart()!=null&& vo.getStatisticsDateEnd()!=null){
	        param.put("startTime", vo.getStatisticsDateStart());
	        param.put("endTime", vo.getStatisticsDateEnd());
        }else {
        	param.put("startTime", LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toInstant(ZoneOffset.of("+8")).toEpochMilli());
        	param.put("endTime", LocalDateTime.of(LocalDate.now(), LocalTime.MAX).toInstant(ZoneOffset.of("+8")).toEpochMilli());
        }
        
        List<ChatVideos> list = chatVideosMapper.statisticsVideosByType(param);
        if (!list.isEmpty()){
            for (ChatVideos chatVideos:list){
                NumberFormat nt = NumberFormat.getPercentInstance();//获取格式化对象
                nt.setMinimumFractionDigits(2);//设置百分数精确度2即保留两位小数
                try {
                    chatVideos.setConnectionRate(nt.format(chatVideos.getAnswerCount()/(double)chatVideos.getVideoCount()));
                } catch (ArithmeticException e) {
                    chatVideos.setConnectionRate("0%");
                }

            }
        }

        return list;

    }


    /**
     *音视频总次数折线图统计0点到23点
     * @return
     */
    public List<ChatVideos> videoAndAudioTotalLineStatistics( ChatVideosSearchVo vo){
      
        Map<String,Object> param=Maps.newHashMap();
        param.put("tenantId", KefuContext.getKefuContext().getTenantId());
        if (vo.getStatisticsDateStart()!=null&& vo.getStatisticsDateEnd()!=null){
        	param.put("startTime", vo.getStatisticsDateStart());
        	param.put("endTime", vo.getStatisticsDateEnd());
            if(DateUtil.isSameDay(DateUtil.date(vo.getStatisticsDateStart()),DateUtil.date(vo.getStatisticsDateEnd()))){
            	param.put("groupType", "dateTime");
            }else {
            	param.put("groupType", "date");
            }

        }else {
        	param.put("groupType", "dateTime");
        	param.put("startTime", LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toInstant(ZoneOffset.of("+8")).toEpochMilli());
        	param.put("endTime", LocalDateTime.of(LocalDate.now(), LocalTime.MAX).toInstant(ZoneOffset.of("+8")).toEpochMilli());
        }
        List<ChatVideos> videos = chatVideosMapper.statisticsVideosByDateTime(param);
        for (ChatVideos video:videos){
        	if(video!=null){
        		NumberFormat nt = NumberFormat.getPercentInstance();//获取格式化对象
        		nt.setMinimumFractionDigits(2);//设置百分数精确度2即保留两位小数
        		try {
        			video.setConnectionRate(nt.format(video.getAnswerCount()/(double)video.getVideoCount()));
        		} catch (ArithmeticException e) {
        			video.setConnectionRate("0%");
        		}
        	}
        	
        }
        return videos;


    }


    public void videoStatisticsExport(ChatVideosSearchVo vo, HttpServletResponse response) throws IOException {
    	 List<ChatVideos> list=videoStatistics(vo);

        //创建导出列表
        List<Object[]> exportList = new ArrayList<>();
        //定义表头
        Object[] title = {msg("音视频次数"), msg("音视频通话总时间"), msg("音频通话次数"),
                msg("视频通话次数"), msg("呼入次数"), msg("音视频童话平均时间"), msg("流量总计"),
                msg("未接听次数"), msg("已接听的次数"), msg("音视频通话接听率")
               };
        exportList.add(title);
        if (!list.isEmpty()){
            for (ChatVideos videos:list){
                Object[] row={videos.getVideoCount(),videos.getVideoTimes(),videos.getAudioType(),
                        videos.getVideoTypes(),videos.getInType(),videos.getVideoTimeAvg(),videos.getFlowSum(),
                        videos.getNoAnswerCount(),videos.getAnswerCount(),videos.getConnectionRate()
                };
                exportList.add(row);
            }
        }
        csvWriter(exportList, response);



    }
}